<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-s-custom"></i> 学生管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button
                    type="primary"
                    icon="el-icon-delete"
                    class="handle-del mr10"
                    @click="delAllSelection"
                >批量删除</el-button>

                <el-input v-model="query.sname"
                          placeholder="请输要查询的姓名"
                          class="handle-input mr10">
                </el-input>

                <el-input v-model="query.sid"
                          placeholder="请输要查询的身份证号"
                          class="handle-input mr10">
                </el-input>

                <el-input v-model="query.sno"
                          placeholder="请输要查询的学号"
                          class="handle-input mr10">
                </el-input>

                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>

                <el-button type="danger" icon="el-icon-plus" class='mr10' @click="handleAdd">新增</el-button>

                <el-button type="info" icon='el-icon-folder-add' @click="handleImport">批量导入</el-button>

                <el-button type="info" icon='el-icon-folder-remove' @click='handleExportAll'>导出全部</el-button>
                <br><br>
                <!--选择学院查询-->
                <el-button type="primary"
                           class="handle-del mr10"
                           icon='el-icon-folder-remove'
                           @click='handleExportSelected'>批量导出</el-button>
                <el-select v-model="query.selectedAca_search"
                           filterable
                           value-key="aname"
                           placeholder="请选择学院"
                           class='handle-select mr10'
                           @change='acaChanged'
                           clearable>
                    <el-option
                        v-for="item in query.selectedAcaOptions"
                        :key="item.aname"
                        :label="item.aname"
                        :value="item">
                    </el-option>
                </el-select>

                <!--选择班级查询-->
                <el-select v-model="query.selectedClass_search"
                           filterable
                           value-key="cname"
                           :disabled='classDisable'
                           class='handle-select '
                           placeholder="请选择班级"
                           clearable>
                    <el-option
                        v-for="item in query.selectedClassOptions"
                        :key="item.cname"
                        :label="item.cname"
                        :value="item">
                    </el-option>
                </el-select>

            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="sname" label="姓名"></el-table-column>
                <el-table-column prop="sid" label="身份证号"></el-table-column>
                <el-table-column prop="sno" label="学号"></el-table-column>
                <el-table-column prop="sex" label="性别"></el-table-column>
                <el-table-column prop="stel" label="电话"></el-table-column>
                <el-table-column prop="address" label="住址"></el-table-column>
                <el-table-column prop="dno" label="寝室号"></el-table-column>
                <el-table-column prop="cname" label="班级"></el-table-column>
                <el-table-column prop="aname" label="学院"></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                            @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handlePageChange"
                    :current-page="query.pageIndex"
                    :page-sizes="[10, 50, 100, 500]"
                    :page-size="query.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pageTotal">
                </el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog :title="title" :visible.sync="editVisible" width="30%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="姓名">
                    <el-input v-model="form.sname"></el-input>
                </el-form-item>
                <el-form-item label="身份证号">
                    <el-input v-model="form.sid"></el-input>
                </el-form-item>
                <el-form-item label="学号">
                    <el-input v-model="form.sno"></el-input>
                </el-form-item>
                <el-form-item label="性别">
                    <el-input v-model="form.sex"></el-input>
                </el-form-item>
                <el-form-item label="电话">
                    <el-input v-model="form.stel"></el-input>
                </el-form-item>
                <el-form-item label="住址">
                    <el-input v-model="form.address"></el-input>
                </el-form-item>
                <el-form-item label="寝室号">
                    <el-input v-model="form.dno"></el-input>
                </el-form-item>
                <el-form-item label="学院">
                    <el-select v-model="asvalue"
                               filterable
                               placeholder="请选择学院"
                               class='handle-select mr10'
                               @change='acaSChanged'
                               clearable>
                        <el-option
                            v-for="item in asoptions"
                            :key="item.ano"
                            :label="item.aname"
                            :value="item.ano">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="班级">
                    <el-select v-model="csvalue"
                               :disabled='classSDisable'
                               class='handle-select '
                               placeholder="请选择班级"
                               clearable>
                        <el-option
                            v-for="item in csoptions"
                            :key="item.cno"
                            :label="item.cname"
                            :value="item.cno">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="done">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 批量导入弹出框 -->
        <el-dialog :title="title" :visible.sync="importVisible" width="30%">
            <el-upload
                class="upload-demo"
                action="http://127.0.0.1:8080/excel/import"
                multiple
                :limit="3"
                :on-success='handleSuccess'>
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: 'testTable',
    data() {
        return {
            //编辑框中下拉框
            asoptions:[],
            asvalue:'',
            csoptions:[],
            cavalue:'',
            //学生表格相关
            csvalue:'',
            title: "",
            query: {
                //提供查询项：姓名、身份证号、学号、寝室号、班级、学院
                sname: '',
                sid: '',
                sno: '',
                dno: '',
                //学院选择框数据
                selectedAcaOptions: [],
                selectedAca_search: {},
                //班级选择框数据
                selectedClassOptions:[],
                selectedClass_search:{},
                pageIndex: 1,
                pageSize: 10
            },
            pageTotal: 0,
            tableData: [],
            multipleSelection: [],
            //控制新增和编辑弹出框
            editVisible: false,
            //控制批量导入弹出框
            importVisible:false,
            form: {},
            //班级查询是否禁用,true是禁用
            classDisable:true,
            classSDisable:true,
            //班级表格数据存放
            classes:[],
        };
    },
    created() {
        this.getData();
        this.getAcaoptions_select();
    },
    beforeRouteEnter(to, from, next) {
        next(vm => {
            vm.jumpIn();
        });
    },
    methods: {
        // 获取 所有学生 的模拟数据
        getData() {
            this.$http.post('/student/pageQuery',{
                    "currentPage": this.query.pageIndex,
                    "pageSize": this.query.pageSize,
                    "snameK": this.query.sname,
                    "snoK": this.query.sno,
                    "sidK": this.query.sid,
                    "dnoK": "",
                    "cnameK": this.query.selectedClass_search.cname,
                    "anameK":this.query.selectedAca_search.aname
                }).then((res)=>{//回调函数
                    this.tableData = res.data.records
                    this.pageTotal = res.data.totalElements;
            })
        },
        //路由转跳时更新界面
        jumpIn(){
            if (this.$route.query.aca!=null) {
                this.query.selectedAca_search =  this.$route.query.aca
                this.getClassOptions_select()
                this.query.selectedClass_search = this.$route.query.class
                this.classDisable = false
                this.getData();
            }
        },

        //获取学院下拉框中数据
        getAcaoptions_select(){
            this.$http.get('/academy',{
            }).then((res)=>{
                this.query.selectedAcaOptions=res.data;
            })
        },

        //获取班级下拉框中数据
        getClassOptions_select(){
            this.$http.post('/class/selectAll',{
                "currentPage": 1,
                "pageSize": 9999999,
                "anoK": this.query.selectedAca_search.ano,
                "teacherNameK": "",
                "cnameK": ""
            }).then((res)=>{
                console.log(res)
                this.query.selectedClassOptions=res.data.records;
            })
        },

        //改变班级查询状态的方法
        acaChanged(aca){
            if(aca!=null){
                this.getClassOptions_select();
                this.query.selectedClass_search = "";
                this.classDisable=false;
            }
            if(aca===''){
                this.classDisable=true;
            }
        },

        //改变编辑弹出框班级查询状态的方法
        acaSChanged(aca){
            console.log(aca)
            if(aca!=null){
                this.classSDisable=false;
            }
            if(aca===''){
                this.classSDisable=true;
            }
        },

        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.getData();
        },

        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.$http.delete('/student/' + row.sid).then((res)=>{//回调函数
                        if (res.data.code === 200) {
                            this.getData();
                            this.$message.success('删除成功');
                        }else {
                            this.$message.error(res.data.msg);
                        }
                    })
                    this.tableData.splice(index, 1);
                })
        },

        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        delAllSelection() {
            let ids = this.multipleSelection.map(item => item.sid)
            this.$http.delete('/student/batchDelete', {data: ids}).then(()=>{//回调函数

                this.$message.error('已删除');
                this.getData();

        })
            this.multipleSelection = [];
        },

        // 编辑操作
        handleEdit(index, row) {
            this.title = "编辑"
            //生成row的副本，防止修改原数据
            this.form = Object.assign({}, row);
            this.editVisible = true;
        },

        //点击确定按钮判断是新增学生还是编辑学生信息
        done(){
            if(this.title==="编辑"){//弹出框title是编辑就是更新
                this.edit()
            }else {
                this.save()
            }
        },

        // 新增操作
        handleAdd(){
            this.form = {};
            this.title = "新增学生";
            this.editVisible = true;
        },

        //  新增学生
        save() {
            console.log('hello');
            this.$http.post("/student", {
                "sid": this.form.sid,
                "sname": this.form.sname,
                "sno": this.form.sno,
                "sex": this.form.sex,
                "stel": this.form.stel,
                "address": this.form.address,
                "dno": this.form.dno,
                "cno":this.csvalue,
            })
                .then((res)=>{
                    console.log(res)
                    if (res.data.code === 200) {
                        this.editVisible = false;

                        this.$message({

                            message: res.data.message,
                            type: 'success'
                        });
                        this.getData();
                    }else {
                        this.$message({
                            message: res.data.message,
                            type: 'error'
                        });
                    }
                })
        },

        // 编辑学生信息
        edit() {
           // console.log('hello')
            this.$http.put("/student", {
                "sid": this.form.sid,
                "sname": this.form.sname,
                "sno": this.form.sno,
                "sex": this.form.sex,
                "stel": this.form.stel,
                "address": this.form.address,
                "dno": this.form.dno,
                "cno":this.csvalue,
            })
                .then((res)=>{
                    console.log(res)
                    if (res.data.code === 200) {
                        this.editVisible = false;

                        this.$message({
                            message: res.data.message,
                            type: 'success'
                        });
                        this.getData();
                    }else {
                        this.$message({
                            message: res.data.message,
                            type: 'error'
                        });
                    }
                })
        },

        //批量导入框
        handleImport(){
            this.title = "批量导入";
            this.importVisible = true;
        },

        //批量导入提示
        handleSuccess(res){
            if (res.code === 200) {
                this.$message({
                    message: res.message,
                    type: 'success'
                });
                this.getData();
            }else {
                this.$message({
                    message: res.data.message,
                    type: 'error'
                })
            }
            this.importVisible = false;
            this.$refs.upload.clearFiles();
        },
        //todo 文件有误
        //批量导出
        handleExportAll(){
            this.$http({
                url: '/excel/download',
                method: 'get',
                responseType: 'arraybuffer'
            }).then((res)=>{
                const blob = new Blob([res.data], { type: 'application/octet-stream' })
                const url = URL.createObjectURL(blob)
                const link = document.createElement('a')
                link.href = url
                link.download = 'template.xlsx'
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
            })
        },

        //导出所选数据
        handleExportSelected(){
            let ids = this.multipleSelection.map(item => item.sid)
            this.$http({
                url: '/excel/selectDownload',
                method: 'post',
                data: ids,
                responseType: 'arraybuffer'
            }).then((res)=>{
                const blob = new Blob([res.data], { type: 'application/octet-stream' })
                const url = URL.createObjectURL(blob)
                const link = document.createElement('a')
                link.href = url
                link.download = 'template.xlsx'
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
            })
        },

        // 每页条数更改
        handleSizeChange(val) {
            this.$set(this.query, 'pageIndex', 1);
            this.$set(this.query, 'pageSize', val);
            this.getData();
        },

        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 180px;
}

.handle-input {
    width: 180px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}

</style>
